import {getDeviceData} from '@/api/biz/deviceData';
import {listFuncByDeviceCode} from '@/api/biz/productFunc';

export default {

  timers: [],

  //记录设备的属性定义，key: 设备编码  value: 设备所属产品的属性map
  deviceAttrMap: {},

  /**
   * 根据配置获取数据
   * @param setting 配置
   * @param params 参数
   * @param callback 回调
   */
  loadData(setting, params, callback) {
    let deviceCode = null;
    if (setting.deviceCode === '&deviceCode') {
      deviceCode = params.deviceCode;
    } else {
      deviceCode = setting.deviceCode;
    }
    if (!deviceCode) {
      return;
    }
    const signalCode = setting.attr;

    if (this.deviceAttrMap[deviceCode]) {
      this.queryData(deviceCode, signalCode, callback);
    } else {
      //查询设备所属产品的属性
      listFuncByDeviceCode(deviceCode).then(res => {
        this.deviceAttrMap[deviceCode] = res.data.reduce((prev, item) => {
          prev[item.code] = item;
          return prev;
        }, {});

        this.queryData(deviceCode, signalCode, callback);
      });
    }

    //定时查询设备数据 TODO 改成 eventbus 监听
    const timer = setInterval(() => {
      this.queryData(deviceCode, signalCode, callback);
    }, 30 * 1000);
    this.timers.push(timer);
  },

  queryData(deviceCode, signalCode, callback) {
    const query = {
      deviceCode: deviceCode,
      validDeviceStatus: true
    };
    if (signalCode) {
      query.signalCode = signalCode;
    }
    //查询设备数据
    getDeviceData(query).then(res => {
      const data1 = Object.assign({}, res.data); //原始数据
      const data2 = this.processDeviceData(deviceCode, res.data); //处理后的数据，代码转名称，单位等
      if (signalCode) {
        const val = data1[signalCode] || '';
        const val2 = data2[signalCode] || '';
        callback(val, val2);
      } else {
        callback(data1, data2);
      }
    }).catch(() => {
      callback();
    });
  },

  /**
   * 处理待展示的设备数据
   * 转换数据值，增加单位
   */
  processDeviceData(deviceCode, deviceData) {
    const data = Object.assign({}, deviceData);
    const attrMap = this.deviceAttrMap[deviceCode];
    // console.log(data, attrMap);
    for (let key in data) {
      let val = data[key];
      const attr = attrMap[key];
      if (!attr) {
        continue;
      }
      //属性的数据定义
      const def = attr.dataDef ? JSON.parse(attr.dataDef) : {};
      //布尔类型和枚举类型，需要代码转名称
      if (attr.dataType === 'bool' || attr.dataType === 'enum') {
        val = String(parseInt(val));
        val = def[val] ? def[val] : val;
      }
      //如果有单位，加上单位
      if (def.unit) {
        val += ' ' + def.unit;
      }
      data[key] = val;
    }
    return data;
  },

  destroy() {
    this.timers.forEach(item => {
      clearInterval(item);
    });
  }

}
